#/* ------------------------------------------------------------------------------
# * Copyright (c) 2006 Novell, Inc. All Rights Reserved.
# *
# *
# * This program is free software; you can redistribute it and/or modify it under
# * the terms of version 2 of the GNU General Public License as published by the
# * Free Software Foundation.
# *
# * This program is distributed in the hope that it will be useful, but WITHOUT
# * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License along with
# * this program; if not, contact Novell, Inc.
# *
# * To contact Novell about this file by physical or electronic mail, you may find
# * current contact information at www.novell.com.
# * ------------------------------------------------------------------------------
# */
#
#/**
# * File:        include/qwe/dialogs.ycp
# * Package:        Configuration of qwe
# * Summary:        Dialogs definitions
# * Authors:        jeff <jeff>
# *
# * $Id: dialogs.ycp 27914 2006-02-13 14:32:08Z locilka $
# */

################################################################################
# Imports
################################################################################

import ycp
import EducationGroup
import EducationUser

from ycp import *
from YCPDeclarations import YCPDeclare
from EducationGUIHelper import *
from Education import *

import_module("Wizard")
import_module("UI")
import_module("Popup")
import_module("Confirm")
import_module('Label')
import_module('FileUtils')
ycp.widget_names('Widgets')

import Widgets
from Widgets import *
from ycp import *

##
 # Set textdomain
 #
import gettext
gettext.install("education")

from EducationHelps import HELPS

################################################################################
# Module Variables
################################################################################

group_csv_file = ""
user_csv_file = ""

################################################################################
# Functions
################################################################################

def import_group_wizard():

  global group_csv_file
  group_csv_file = ""

  ycp.Wizard.CreateDialog()
  
  Wizard.RestoreAbortButton()
  Wizard.SetAbortButton(sym('cancel'),Label.CancelButton())

  aliases = {
    "browse": Code(ImportGroupDialog),
    "results":  Code(ImportGroupResultsDialog)
  }

  sequence = {
    "ws_start": "browse",
    "browse": {
      Symbol("back"): Symbol("cancel"),
      Symbol("next"): "results"
    },
    "results": {
      Symbol("cancel"): Symbol("cancel"),
      Symbol("back"): "browse",
      Symbol("next"): Symbol("import")
    }
  }

  ret = ycp.Sequencer.Run(aliases, sequence)
  print ret
  UI.CloseDialog()
  return ret

def import_user_wizard():

  global user_csv_file
  user_csv_file = ""

  ycp.Wizard.CreateDialog()

  Wizard.RestoreAbortButton()
  Wizard.SetAbortButton(sym('cancel'),Label.CancelButton())

  aliases = {
    "browse": Code(ImportUserDialog),
    "results":  Code(ImportUserResultsDialog)
  }

  sequence = {
    "ws_start": "browse",
    "browse": {
      Symbol("back"): Symbol("cancel"),
      Symbol("next"): "results"
    },
    "results": {
      Symbol("cancel"): Symbol("cancel"),
      Symbol("back"): "browse",
      Symbol("next"): Symbol("import")
    }
  }

  ret = ycp.Sequencer.Run(aliases, sequence)
  print ret
  UI.CloseDialog()
  return ret

def get_error_table_data(errors):

  error_table_data = []

  for error in errors:
    parts = error.split(":")
    error_table_data.append(item(parts[0], [parts[0], parts[1]]))

  return error_table_data

def get_import_groups_table_data(imported_groups):

  groups = []

  for group in imported_groups:
    
    group_name_cell = icon_cell("yast-education-group.png", group.name)
    friendly_name = group.friendly_name

    if (group.age_range_end == 125):
      age_range = str(group.age_range_start) + " and up"
    else:
      age_range = str(group.age_range_start) + "-" + str(group.age_range_end)

    sabayon_profile = group.sabayon_profile
    kiosk_profile = group.kiosk_profile

    groups.append(item(group.name, [group_name_cell, friendly_name, age_range, sabayon_profile, kiosk_profile]))

  return groups

def get_import_users_table_data(imported_users):

  users = []

  for user in imported_users:
    
    username_cell = icon_cell("yast-education-user.png", user.username)
    full_name = user.full_name
    group = user.group and user.group.name or "None"
    auto_login = (user.auto_login and "Yes" or "No")
    enabled = (user.enabled and "Yes" or "No")

    users.append(item(user.username, [username_cell, full_name, group, auto_login, enabled]))

  return users

#/**
# * Step 1 of the group import dialog
# * @return dialog result
# */
@YCPDeclare("symbol")
def ImportGroupDialog():

    global group_csv_file

    header_text = """This wizard allows you to batch import a list of groups from a comma-separated value (CSV)
file.  For details on the format of the file, please click the Help button."""

    caption = _("Import Groups");
    
    contents = \
      VBox(
        Left(
          HBox(
            HSpacing(1),
            Widgets.Label(header_text)
          )
        ),
        VStretch(),
        HBox(
          HSpacing(1),
          TextEntry(id("csv_file"), _("C&SV file:"), group_csv_file),
          VBox(
            Widgets.Label(""),
            PushButton(id("browse"), Label.BrowseButton())
          ),
          HSpacing(1)
        ),
        VStretch()
      )

    ycp.Wizard.SetContentsButtons(caption, contents, "",
            ycp.Label.BackButton(), ycp.Label.NextButton())

    Wizard.HideBackButton()
    ret = None

    while True:

        ret = ycp.UI.UserInput()
        print ret

        if (response_was(ret, "browse")):
          file = UI.AskForExistingFile("/etc", "*.csv", "Select the groups file to import")

          if (file):
            UI.ChangeWidget(id('csv_file'), sym('Value'), file)
        
        if ret == Symbol("cancel"):
            break
        elif ret == Symbol("next"):
          csv_file = UI.QueryWidget(id('csv_file'), sym('Value')).strip()
          if (len(csv_file) == 0):
              Popup.Error("Please specify a CSV file from which to import groups.")
              continue
          elif not FileUtils.Exists(csv_file):
            Popup.Error("The specified file does not exist.")
            continue
          elif not FileUtils.IsFile(csv_file):
            Popup.Error("The specified path is not a file.")
            continue
          else:
            group_csv_file = csv_file
            break

    return ret

#/**
# * Step 2 of the group import dialog
# * @return dialog result
# */
@YCPDeclare("symbol")
def ImportGroupResultsDialog():
    
    caption = _("Import Groups")
    
    contents = \
      VBox(
        Frame("Groups to import",
          VBox(
            Left(Widgets.Label("The following groups will be imported:")),
            Table(id('groups_table'), notify_opt(),
            table_header([_("Group"), _("Friendly Name"), _("Age Range"), _("Sabayon Profile"), _("Kiosk Profile")]), []),
          )
        ),
        Frame("Errors",
        VBox(
            Left(Widgets.Label("The following errors occurred during the import process:")),
            Table(id('errors_table'), notify_opt(),
            table_header([_("Line"), _("Error Message")]), [])
          )
        )
      )

    ycp.Wizard.SetContentsButtons(caption, contents, "",
            ycp.Label.BackButton(), _(" I&mport "))

    ret = None

    global group_csv_file

    (imported_groups, errors) = EducationGroup.import_groups(group_csv_file)

    UI.ChangeWidget(id('groups_table'), sym('Items'), get_import_groups_table_data(imported_groups))
    UI.ChangeWidget(id('errors_table'), sym('Items'), get_error_table_data(errors))

    while True:
        ret = ycp.UI.UserInput()
      
        if ret == Symbol("cancel") or ret == Symbol("back"):
            break
        elif ret == Symbol("next"):

          for group in imported_groups:
            group.save()
          
          break
                
    return ret

#/**
# * Step 1 of the user import dialog
# * @return dialog result
# */
@YCPDeclare("symbol")
def ImportUserDialog():

    global user_csv_file

    header_text = """This wizard allows you to batch import a list of users from a comma-separated value (CSV)
file.  For details on the format of the file, please click the Help button."""

    caption = _("Import Users");

    contents = \
      VBox(
        Left(
          HBox(
            HSpacing(1),
            Widgets.Label(header_text)
          )
        ),
        VStretch(),
        HBox(
          HSpacing(1),
          TextEntry(id("csv_file"), _("C&SV file:"), user_csv_file),
          VBox(
            Widgets.Label(""),
            PushButton(id("browse"), Label.BrowseButton())
          ),
          HSpacing(1)
        ),
        VStretch()
      )

    ycp.Wizard.SetContentsButtons(caption, contents, "",
            ycp.Label.BackButton(), ycp.Label.NextButton())

    Wizard.HideBackButton()
    ret = None

    while True:

        ret = ycp.UI.UserInput()
        print ret

        if (response_was(ret, "browse")):
          file = UI.AskForExistingFile("/etc", "*.csv", "Select the users file to import")

          if (file):
            UI.ChangeWidget(id('csv_file'), sym('Value'), file)

        if ret == Symbol("cancel"):
            break
        elif ret == Symbol("next"):
          csv_file = UI.QueryWidget(id('csv_file'), sym('Value')).strip()
          if (len(csv_file) == 0):
              Popup.Error("Please specify a CSV file from which to import users.")
              continue
          elif not FileUtils.Exists(csv_file):
            Popup.Error("The specified file does not exist.")
            continue
          elif not FileUtils.IsFile(csv_file):
            Popup.Error("The specified path is not a file.")
            continue
          else:
            user_csv_file = csv_file
            break

    return ret

#/**
# * Step 2 of the user import dialog
# * @return dialog result
# */
@YCPDeclare("symbol")
def ImportUserResultsDialog():

    caption = _("Import Users")

    contents = \
      VBox(
        Frame("Users to import",
          VBox(
            Left(Widgets.Label("The following users will be imported:")),
            Table(id('users_table'), notify_opt(),
            table_header([_("Username"), _("Full name"), _("Education group"), _("Automatic Login"), _("Enabled")]), []),
          )
        ),
        Frame("Errors",
        VBox(
            Left(Widgets.Label("The following errors occurred during the import process:")),
            Table(id('errors_table'), notify_opt(),
            table_header([_("Line"), _("Error Message")]), [])
          )
        )
      )

    ycp.Wizard.SetContentsButtons(caption, contents, "",
            ycp.Label.BackButton(), _(" I&mport "))

    ret = None

    global user_csv_file
    
    (imported_users, errors) = EducationUser.import_users(user_csv_file)
    
    UI.ChangeWidget(id('users_table'), sym('Items'), get_import_users_table_data(imported_users))    
    UI.ChangeWidget(id('errors_table'), sym('Items'), get_error_table_data(errors))
    
    while True:
      
        ret = ycp.UI.UserInput()

        if ret == Symbol("cancel") or ret == Symbol("back"):

            break
            
        elif ret == Symbol("next"):

          for user in imported_users:
            user.save()
          
          break

    return ret
